package in.srain.cube;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;

import in.srain.cube.util.LocalDisplay;
import in.srain.cube.util.NetworkStatusManager;

import java.util.List;

public class Cube {

    private static Cube instance;

    private Application mApplication;
    private boolean mIsMainProcess;
    private String mProcessName;

    private Cube(Application application) {
        mApplication = application;

        // local display
        LocalDisplay.init(application);

        // network status
        NetworkStatusManager.init(application);

        mIsMainProcess = checkIsMainProcess(application);
    }

    public static void onCreate(Application app) {
        instance = new Cube(app);
    }

    public static Cube getInstance() {
        return instance;
    }

    public Context getContext() {
        return mApplication;
    }

    private boolean checkIsMainProcess(Context context) {
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfoList = am.getRunningAppProcesses();
        String mainProcessName = context.getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfoList) {
            if (info.pid == myPid) {
                mProcessName = info.processName;
                if (mainProcessName.equals(info.processName)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isInForeground(@NonNull Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        if (runningAppProcesses == null) {
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo runningAppProcess : runningAppProcesses) {
            if (runningAppProcess.processName.equals(context.getPackageName()) &&
                    runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    public boolean isMainProcess() {
        return mIsMainProcess;
    }

    public String getProcessName() {
        return mProcessName;
    }
}
